package com.yootk.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 登录检测过滤
 */
@WebFilter(
        urlPatterns = {"/pages/index/*"}, // 过滤路径
        initParams = { // 初始化参数
                @WebInitParam(name = "auth", value = "id")
        })
public class LoginFilter extends HttpFilter { // 定义编码过滤类
    private String auth; // 保存session的检验标记

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.auth = filterConfig.getInitParameter("auth"); // 接收初始化参数
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (this.auth != null) {    // 现在需要进行验证
            if (request.getSession().getAttribute(this.auth) != null) { // 属性存在
                chain.doFilter(request, response); // 正常访问
            } else {    // 属性不存在
                request.getRequestDispatcher("/pages/login.jsp").forward(request, response);
            }
        } else { // 如果没有设置session属性名称，不需要验证
            chain.doFilter(request, response); // 直接转发到目标访问路径
        }
    }
}
